<template>
  <el-upload :limit="1" action="" :multiple="false" :before-upload="importExcel" accept=".xls,.xlsx" :show-file-list="false">
    <slot></slot>
  </el-upload>
</template>

<script>
import * as XLSX from 'xlsx';
export default {
  // 处理excel文件上传并转化为json数据，支持表头-数据格式
  name: 'ExcelUpload',
  data() {
    return {};
  },
  methods: {
    importExcel(file) {
      try {
        const reader = new FileReader();

        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array', cellDates: true });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          // Assuming the first row is the header
          const headers = jsonData[0];
          const rows = jsonData.slice(1);

          const formattedData = rows.map((row) => {
            let rowData = {};
            headers.forEach((header, index) => {
              rowData[header] = row[index];
            });
            return rowData;
          });

          console.log('formattedData', formattedData);
          this.$emit('update', formattedData);
        };

        reader.readAsArrayBuffer(file);
      } catch (e) {
        this.msgError(e);
      }

      return false;
    }
  }
};
</script>
